<template>
  <div>
    <!-- 面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图-->
    <el-card>
      <!-- 添加角色按钮-->
      <el-row>
        <el-col>
          <el-button type="primary"
                     @click="addRolesDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域-->
      <el-table :data="rolelist"
                style="width: 100%"
                border
                stripe>
        <!-- 展开列-->
        <el-table-column type="expand">
          <!-- 通过插值得到角色值-->
          <template slot-scope="scope">
            <!-- 渲染一级权限
            class = if i1索引 === 0 加上bdtop边框线-->
            <el-row v-for="(item1, i1) in scope.row.children"
                    :key="item1.id"
                    :class="['bdbottom', i1 === 0 ? 'bdtop': '','vcenter']">
              <el-col :span='5'>
                <el-tag @close="removeRightById(scope.row,item1.id)"
                        closable> {{item1.authName}} </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级,三级权限
              i2 索引是第一个不加上边框线 下边框由上一个边框线组成-->
              <el-col :span='19'>
                <el-row v-for="(item2, i2) in item1.children"
                        :key='item2.id'
                        :class="[i2 === 0 ? '': 'bdtop','vcenter']">
                  <!-- 渲染二级权限-->
                  <el-col :span="7">
                    <el-tag type='success'
                            @close="removeRightById(scope.row,item2.id)"
                            closable> {{item2.authName}} </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限-->
                  <el-col :span="17">
                    <el-tag v-for="item3 in item2.children"
                            :key='item3.id'
                            type='warning'
                            @close="removeRightById(scope.row,item3.id)"
                            closable>
                      {{item2.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <!-- 索引列-->
        <el-table-column label="#"
                         type="index">
        </el-table-column>
        <el-table-column prop="roleName"
                         label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc"
                         label="角色描述"></el-table-column>
        <el-table-column label="操作"
                         width="300px">
          <template slot-scope="scope">
            <el-button size="mini"
                       type="primary"
                       icon="el-icon-edit"
                       @click="editRoles(scope.row.id)">编辑</el-button>
            <el-button size="mini"
                       type="danger"
                       icon="el-icon-delete"
                       @click="removeRolesById(scope.row.id)">删除</el-button>
            <el-button size="mini"
                       type="warning"
                       icon="el-icon-setting"
                       @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog title="添加用户"
               :visible.sync="addRolesDialogVisible"
               width="50%"
               @close="addDialogClosed">

        <el-form label-position='left'
               :rules="FromRules"
               ref="addRolesFormRef"
               label-width="80px"
               :model="RolesFromsData">
        <el-form-item label="角色名称"
                      prop="roleName">
          <el-input v-model="RolesFromsData.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述"
                      prop="roleDesc">
          <el-input v-model="RolesFromsData.roleDesc"></el-input>
        </el-form-item>
        </el-form>
        <span slot="footer"
            class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

        <!-- 修改角色的对话框-->
    <el-dialog title="编辑角色"
               :visible.sync="editRolesDialogVisible"
               width="50%"
               @close="editRolesDialogClosed">
      <el-form ref="editRolesFormRef"
               :rules="FromRules"
               :model="RolesFromsData"
               label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="RolesFromsData.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述"
                      prop="roleDesc">
          <el-input v-model="RolesFromsData.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editRolesInfo">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="分配权限"
               :visible.sync="setRightDialogVisble"
               width="50%" @close='setRightDialogClosed'>
            <!-- Tree树型控件  props绑定数据源
            default-checked-keys  默认勾选节点的key数组(已有权限默认勾选)-->
      <el-tree :data="rightlist"
               :props="treeProps"
               show-checkbox
               node-key="id"
               default-expand-all
               :default-checked-keys='defKeys'
               ref="treeRef">
      </el-tree>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="setRightDialogVisble = false">取 消</el-button>
        <el-button type="primary"
                   @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 角色列表数据
      rolelist: [],
      // 分配权限对话框
      setRightDialogVisble: false,
      // 所有权限数据
      rightlist: {},
      // 添加角色对话框显示与隐藏
      addRolesDialogVisible: false,
      // 角色数据与响应
      RolesFromsData: {},
      // 角色校验规则
      FromRules: {
        roleName: [{
          required: true,
          message: '请输入角色名称',
          tigger: 'blur'
        }],
        roleDesc: [{
          required: true,
          message: '请输入角色描述',
          tigger: 'blur'
        }]
      },
      // 编辑角色对话框显示与隐藏
      editRolesDialogVisible: false,
      // 树性控件的熟悉绑定对象
      treeProps: {
        // 绑定数据名
        label: 'authName',
        // 循环哪一项
        children: 'children'
      },
      // 默认选中节点的ID值
      defKeys: [],
      // 分配角色权限的角色ID
      roldId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取所有角色列表
    // async await 简化异步请求
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error('获取角色列表失败')
      }
      this.rolelist = res.data
    },
    // 参数: 角色id 权限id
    async removeRightById (role, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      // 将服务器及时返回的权限数据重新赋值已有的权限列表
      // 防止刷新
      role.children = res.data
      this.$message.success('删除权限成功')
    },
    // 展示分配权限的对话框
    async showSetRightDialog (role) {
      // 保存id用于 allotRights()
      this.roldId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限数据失败')
      // 获取权限数据保存到data中
      this.rightlist = res.data
      // 递归获取三级节点的ID
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisble = true
    },
    //  添加用户对话框关闭
    addDialogClosed () {
      // 先监听close事件 在引用ref的resetFields 用于重置表单
      this.$refs.addRolesFormRef.resetFields()
    },
    // 添加角色
    addRoles () {
      // 提交请求前，表单预验证
      this.$refs.addRolesFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请根据提示填写')
        }
        // 发起添加用户的网络请求
        const { data: res } = await this.$http.post('roles', this.RolesFromsData)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        this.addRolesDialogVisible = false
        // 刷新列表数据
        this.getRolesList()
      })
    },
    // 修改角色
    editRolesInfo () {
      // roles/:id  put  id 200
      this.$refs.editRolesFormRef.validate(async valid => {
        // 表单预校验失败
        if (!valid) return this.$message.error('请根据提示填写')
        const { data: res } = await this.$http.put(
          'roles/' + this.RolesFromsData.roleId,
          {
            roleName: this.RolesFromsData.roleName,
            roleDesc: this.RolesFromsData.roleDesc
          }
        )
        if (res.meta.status !== 200) {
          this.$message.error('更新角色信息失败')
        }
        // 隐藏编辑角色对话框
        this.editRolesDialogVisible = false
        this.$message.success('更新角色信息成功')
        this.getRolesList()
      })
    },
    //  编辑角色对话框打开   查询角色
    async editRoles (id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      this.RolesFromsData = res.data
      this.editRolesDialogVisible = true
    },
    // 修改角色对话框关闭
    editRolesDialogClosed () {
      // 重置表格
      this.$refs.editRolesFormRef.resetFields()
    },
    // 删除角色
    async removeRolesById (id) {
      // messageBox弹框提示
      const confirmResult = await this.$confirm('此操作将永久删除该用户,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 用户确认删除,返回字符串 confirm
      // 用户取消删除,返回字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      this.getRolesList()
    },
    // 通过递归形式,获取角色下所有三级权限id并保存到defkeys 数组中
    getLeafKeys (node, arr) {
      // 如果当前node节点不包含children属性,则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 分配权限对话框的关闭事件
    setRightDialogClosed () {
      // 由于不清空,数组会累计数据
      this.defKeys = []
    },
    // 点击角色分配权限
    async allotRights () {
      // 所有选择三级和半选中的二级的keys
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // keys以英文逗号拼接
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roldId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      // 更新列表数据
      this.getRolesList()
      this.setRightDialogVisble = false
    }
  }
}
</script>

<style lang="scss" scoped>
.el-tag{
    margin: 7px;
}
.bdtop{
  // 上边线
  border-top: 1px solid #eee;
}
.bdbottom{
  // 下边线
  border-bottom: 1px solid #eee;
}
// 纵向居中对齐
.vcenter{
  display: flex;
  align-items: center;
}
</style>
